package com.famnote.getitbeauty;



import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;

import com.famnote.getitbeauty.R;


import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.provider.Settings.Secure;
import android.app.Activity;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.telephony.TelephonyManager;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.view.Window;
import android.view.View.OnClickListener;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.Button;

public class MainActivity extends Activity {

	// Debugging
    private static final String TAG = "HomeActivity";
    private static final boolean D = true;
    
    
	private Activity activity;
	
	private Handler mHandler = new Handler();
	
	private ProgressDialog dialog;
	
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
		
		activity = this;
		
		Button button = (Button) findViewById(R.id.button1);
		button.setOnClickListener(new OnClickListener() {
		    public void onClick(View v) {
		       // your code here
		    
		    	
		    	String msg = getResources().getString(R.string.loading);	
		        dialog = ProgressDialog.show(activity, "", msg, true);

		        CheckNickNameTask task = new CheckNickNameTask();

		        /*
		        String androidid = Secure.getString(getContentResolver(), Secure.ANDROID_ID);
		        
		        String url = "http://push.appaas.com/hulbox/of_check_nickname.php?deviceid=" + androidid;
				*/
		        
		        TelephonyManager tm = (TelephonyManager) activity.getSystemService(Context.TELEPHONY_SERVICE);
		        String deviceid = tm.getDeviceId();
		        String url = "http://push.appaas.com/hulbox/rc_check_nickname.php?deviceid=" + deviceid;
		        
		        task.execute(url);
		        
		    	
		    	//Intent i = new Intent(activity, PreviewActivity.class);
             	
             	//startActivity(i);
		    	
		    }
		});
		
		
		String msg = getResources().getString(R.string.loading);
        dialog = ProgressDialog.show(this, "", msg, true);

		TelephonyManager tm = (TelephonyManager) activity.getSystemService(Context.TELEPHONY_SERVICE);
        String deviceid = tm.getDeviceId();
        String url = "http://push.appaas.com/hulbox/rc_popup.php?deviceid=" + deviceid;
        
        PopupTask popupTask = new PopupTask();
        popupTask.execute(url);
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		//getMenuInflater().inflate(R.menu.activity_main, menu);
		return true;
	}

	
    private class WebViewClientClass extends WebViewClient { 
        @Override
        public boolean shouldOverrideUrlLoading(WebView view, String url) { 
            view.loadUrl(url); 
            return true; 
        } 
    }
    
    
	
	/** AsyncTask to download xml data */
    private class CheckNickNameTask extends AsyncTask<String, Integer, String>{
        String data = null;
                
        @Override
        protected String doInBackground(String... url) {
                        try{
                            data = downloadUrl(url[0]);
                                
                        }catch(Exception e){
                        	Log.d("Background Task",e.toString());
                        }
                        if(D) Log.e(TAG, "nickname: " + data);
                        
                        return data;
        }

        @Override
        protected void onPostExecute(String result) {
                	
             dialog.dismiss();
                	
             if ((data == null) || (data == "")) {

      			Intent i = new Intent(activity, RegNickNameActivity.class);
     			startActivity(i); 
            		
             } else {
            	 
            	 String nickname = data;
         		String roomid = "face";
         		
         		
         		Intent i = new Intent(activity, GroupChatActivity.class);
             	
             	i.putExtra("nickname", nickname);
    	
             	i.putExtra("roomid", roomid);

             	startActivity(i);
    			
             }
                	
        }
    }
	
	
	/** A method to download xml data from url */
    private String downloadUrl(String strUrl) throws IOException{
        String data = "";
        InputStream iStream = null;
        try{
                URL url = new URL(strUrl);
                
                // Creating an http connection to communicate with url 
                HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();

                // Connecting to url 
                urlConnection.connect();

                // Reading data from url 
                iStream = urlConnection.getInputStream();
                
                BufferedReader br = new BufferedReader(new InputStreamReader(iStream));
                
                StringBuffer sb  = new StringBuffer();
                
                String line = "";
                while( ( line = br.readLine())  != null){
                	sb.append(line);
                }
                
                
                data = sb.toString();

                br.close();

        }catch(Exception e){
                Log.d("Exception while downloading url", e.toString());
                if(D) Log.e(TAG, e.toString());
        }finally{
                iStream.close();
        }

        return data;
    }
    
    
    
    private class PopupTask extends AsyncTask<String, Integer, String>{
        String data = null;
                
        @Override
        protected String doInBackground(String... url) {
                        try{
                            data = downloadUrl(url[0]);
                                
                        }catch(Exception e){
                        	Log.d("Background Task",e.toString());
                        }
                        if(D) Log.e(TAG, "popup_url: " + data);
                        
                        return data;
        }

        @Override
        protected void onPostExecute(String result) {
                	
             dialog.dismiss();
                	
             if ((data != null) && (data != "")) {
                	final Dialog popupDlg = new Dialog(activity);
            		popupDlg.requestWindowFeature(Window.FEATURE_NO_TITLE);
            		popupDlg.setContentView(R.layout.popup);
            		popupDlg.setCancelable(true);

                    WebView webView = (WebView) popupDlg.findViewById(R.id.webview);
                    webView.getSettings().setJavaScriptEnabled(true);
                    //webView.loadUrl("http://en.wikipedia.org/wiki/" + name.getText().toString());
                    //webView.loadUrl("http://en.wikipedia.org/wiki/" + "gold");
                    //webView.loadUrl("http://blog.naver.com/swingfish");
                    webView.loadUrl(data);
                    webView.setWebViewClient(new WebViewClientClass());
                    
                  
                    Button button = (Button) popupDlg.findViewById(R.id.close);
                    button.setOnClickListener(new OnClickListener() {
            		    public void onClick(View v) {
            		    	popupDlg.dismiss();
            		    }
            		});
                    /*
                    ImageView imgView = (ImageView) popupDlg.findViewById(R.id.close);
            		imgView.setOnClickListener(new OnClickListener() {
            		    public void onClick(View v) {
            		    	popupDlg.dismiss();
            		    }
            		});
                    */
                    /*
                    webView.setOnClickListener(new OnClickListener() {
            		    public void onClick(View v) {
            		    	popupDlg.dismiss();
            		    }
            		});
                    */
                       
                    //dialog.show();
            		
                    
                    mHandler.post(new Runnable() {
                        public void run() {
                        	popupDlg.show();
                        }
                    });
            		
             }
                	
        }
    }
    
    
    
}
